﻿namespace eeenno.SpeeedReaderUI.NativeWebBrowser.Win32
{
    using eeenno.SpeeedReaderUI.NativeWebBrowser.Runtime.InteropServices;
    using System;

    public class WinAPIException : Exception
    {
        private int win32Error;

        public WinAPIException(Exception ex) : base(ex.Message)
        {
            this.win32Error = 0;
        }

        public WinAPIException(string Message) : base(Message + " " + GetErrorMessage(MarshalEx.GetLastWin32Error()))
        {
            this.win32Error = MarshalEx.GetLastWin32Error();
        }

        public WinAPIException(string Message, int ErrorCode) : base(Message + " " + GetErrorMessage(ErrorCode))
        {
            this.win32Error = ErrorCode;
        }

        internal static string GetErrorMessage(int ErrNo)
        {
            IntPtr ptr;
            int len = Core.FormatMessage(Core.FormatMessageFlags.FromSystem | Core.FormatMessageFlags.AllocateBuffer, 0, ErrNo, 0, out ptr, 0, null);
            if (len == 0)
            {
                return string.Format("Error {0} (0x{0:X})", ErrNo);
            }
            string str = MarshalEx.PtrToStringUni(ptr, 0, len);
            MarshalEx.FreeHGlobal(ptr);
            return str;
        }

        public int Win32Error
        {
            get
            {
                return this.win32Error;
            }
        }
    }
}

